package com.vhall.component.service.audit.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.account.AccountMapper;
import com.vhall.component.dao.audit.AuditRecordMapper;
import com.vhall.component.dao.record.RecordMapper;
import com.vhall.component.dao.room.RoomMapper;
import com.vhall.component.entity.account.AccountEntity;
import com.vhall.component.entity.audit.dto.AuditRecordListDTO;
import com.vhall.component.entity.audit.dto.CreateAuditRecordDTO;
import com.vhall.component.entity.audit.entity.AuditRecordEntity;
import com.vhall.component.entity.audit.vo.AuditRecordResponseVO;
import com.vhall.component.entity.record.RecordEntity;
import com.vhall.component.entity.room.entity.RoomsEntity;
import com.vhall.component.framework.common.constant.CommonConstant;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.service.audit.AuditRecordService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xing.wang
 * @description 针对表【audit_record(审核记录表)】的数据库操作Service实现
 * @createDate 2023-08-08 15:27:19
 */
@Service
@RequiredArgsConstructor
public class AuditRecordServiceImpl extends ServiceImpl<AuditRecordMapper, AuditRecordEntity>
        implements AuditRecordService {
    private final AuditRecordMapper auditRecordMapper;
    private final AccountMapper accountMapper;

    private final RecordMapper recordMapper;

    public final RoomMapper roomMapper;
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(CommonConstant.DATETIME_FORMAT);
    @Override
    public List<AuditRecordResponseVO> getAuditRecordList(AuditRecordListDTO dto) {
        LambdaQueryWrapper<AuditRecordEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuditRecordEntity::getAuditTable, dto.getAuditTable())
                .eq(AuditRecordEntity::getAuditTableRecordId, dto.getAuditTableRecordId())
                .orderByDesc(AuditRecordEntity::getId);
        List<AuditRecordEntity> auditRecordEntities = auditRecordMapper.selectList(queryWrapper);
        return buildAuditRecordInfo(auditRecordEntities);
    }

    @NotNull
    private List<AuditRecordResponseVO> buildAuditRecordInfo(List<AuditRecordEntity> auditRecordEntities) {
        List<AuditRecordResponseVO> result = new ArrayList<>();
        if (CollUtil.isNotEmpty(auditRecordEntities)) {
            /**
             * 审核记录创建人 id
             */
            List<Integer> createdByList = auditRecordEntities.stream().map(AuditRecordEntity::getAccountId).distinct().collect(Collectors.toList());
            LambdaQueryWrapper<AccountEntity> accountWhere = Wrappers.lambdaQuery();
            accountWhere.in(AccountEntity::getAccountId, createdByList);
            List<AccountEntity> accountEntityList = accountMapper.selectList(accountWhere);
            Map<Integer, List<AccountEntity>> createInfoMap = accountEntityList.stream().collect(Collectors.groupingBy(AccountEntity::getAccountId));
            for (AuditRecordEntity auditRecordEntity : auditRecordEntities) {
                AuditRecordResponseVO temp = new AuditRecordResponseVO();
                temp.setAuditComments(auditRecordEntity.getAuditComments());
                temp.setAuditStatus(auditRecordEntity.getAuditStatus());
                temp.setId(auditRecordEntity.getId());
                Integer accountId = auditRecordEntity.getAccountId();
                temp.setReviewer(accountId);
                LocalDateTime createdAt = auditRecordEntity.getCreatedAt();
                String reviewTime = createdAt.format(dateTimeFormatter);
                temp.setReviewTime(reviewTime);
                if (createInfoMap.containsKey(accountId)) {
                    List<AccountEntity> accountEntityList1 = createInfoMap.get(accountId);
                    AccountEntity accountEntity = accountEntityList1.get(0);
                    temp.setReviewName(accountEntity.getNickname());
                }
                result.add(temp);
            }
        }
        return result;
    }

    @Override
    public Boolean createAuditRecord(CreateAuditRecordDTO dto) {
        AuditRecordEntity auditRecordEntity = new AuditRecordEntity();
        Token token = TokenThreadLocal.getToken();
        Integer accountId = token.getAccountId();
        auditRecordEntity.setAuditTableRecordId(dto.getAuditTableRecordId());
        auditRecordEntity.setAuditComments(dto.getAuditComments());
        auditRecordEntity.setAuditStatus(dto.getAuditStatus());
        auditRecordEntity.setAuditTable(dto.getAuditTable());
        auditRecordEntity.setReviewerId(accountId);
        auditRecordEntity.setAccountId(accountId);
        auditRecordEntity.setUpdateBy(accountId);
        LocalDateTime now = LocalDateTime.now();
        auditRecordEntity.setCreatedAt(now);
        auditRecordEntity.setUpdatedAt(now);
        auditRecordEntity.setAuditRounds(dto.getAuditRounds());
        int insert = auditRecordMapper.insert(auditRecordEntity);
        return insert >= 1;
    }

    @Override
    public AuditRecordResponseVO getAuditRecord(String auditTableRecordId, String auditTable,Integer auditRounds) {
        LambdaQueryWrapper<AuditRecordEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AuditRecordEntity::getAuditTable, auditTable)
                .eq(AuditRecordEntity::getAuditRounds,auditRounds)
                .eq(AuditRecordEntity::getAuditTableRecordId, auditTableRecordId)
                .orderByDesc(AuditRecordEntity::getId)
                .last(" limit 1");
        AuditRecordEntity auditRecordEntity = auditRecordMapper.selectOne(queryWrapper);
        AuditRecordResponseVO temp = new AuditRecordResponseVO();
        if (auditRecordEntity == null){
            RecordEntity recordEntity = recordMapper.selectById(auditTableRecordId);
            RoomsEntity roomsEntity = roomMapper.selectById(recordEntity.getIlId());
            if (roomsEntity == null){
                LambdaQueryWrapper<RoomsEntity> roomsEntityLambdaQueryWrapper = Wrappers.lambdaQuery();
                roomsEntityLambdaQueryWrapper.eq(RoomsEntity::getRoomId, recordEntity.getRoomId());
                roomsEntityLambdaQueryWrapper.last(" limit 1");
                roomsEntity = roomMapper.selectOne(roomsEntityLambdaQueryWrapper);
            }
            if (roomsEntity.getLiveType() == 2){
                temp.setAuditComments("系统自动过审");
                temp.setAuditStatus(1);
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                temp.setReviewTime(roomsEntity.getEndLiveTime().format(df));
                temp.setReviewName("系统");
            }
            return temp;
        }
        temp.setAuditComments(auditRecordEntity.getAuditComments());
        temp.setAuditStatus(auditRecordEntity.getAuditStatus());
        temp.setId(auditRecordEntity.getId());

        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        temp.setReviewTime(auditRecordEntity.getUpdatedAt().format(df));
        Integer accountId = auditRecordEntity.getAccountId();
        if (accountId == null || accountId == 0){
            temp.setReviewName("系统");
        }else {
            temp.setReviewer(accountId);
            AccountEntity accountEntity = accountMapper.selectById(accountId);
            if (accountEntity != null) {
                temp.setReviewName(accountEntity.getNickname());
            }
        }
        return temp;
    }
}




